/**
 * Copyright 2014-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.certapp.service;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.certapp.common.code.ConstantCode;
import com.certapp.common.exception.BaseException;
import com.certapp.common.properties.ConstantProperties;
import com.certapp.common.utils.CommonUtils;
import com.certapp.dao.entity.TbToken;
import com.certapp.dao.entity.TbTokenExample;
import com.certapp.dao.mapper.TbTokenMapper;
import lombok.extern.log4j.Log4j2;

/**
 * token service.
 */
@Log4j2
@Service
public class TokenService {
    
    @Autowired
    private ConstantProperties properties;
    @Autowired
    private TbTokenMapper tbTokenMapper;

    /**
     * create token.
     */
    public String createToken(String value) {
        if (StringUtils.isBlank(value)) {
            log.error("fail createToken. param is null");
            return null;
        }
        // support guomi
        String token = CommonUtils.shaEncode(UUID.randomUUID() + value);
        // save token
        TbToken tbToken = new TbToken();
        tbToken.setToken(token);
        tbToken.setValue(value);
        tbToken.setExpireTime(LocalDateTime.now().plusSeconds(properties.getAuthTokenMaxAge()));
        tbToken.setCreateTime(LocalDateTime.now());
        tbTokenMapper.insert(tbToken);
        return token;
    }

    /**
     * get value from token.
     */
    public String getValueFromToken(String token) {
        Assert.requireNonEmpty(token, "token is empty");

        // query by token
        TbToken tbToken = tbTokenMapper.selectByPrimaryKey(token);
        if (Objects.isNull(tbToken)) {
            log.warn("fail getValueFromToken. tbToken is null");
            throw new BaseException(ConstantCode.INVALID_TOKEN);
        }
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(tbToken.getExpireTime())) {
            log.warn("fail getValueFromToken. token has expire at:{}", tbToken.getExpireTime());
            // delete token
            this.deleteToken(token, null);
            throw new BaseException(ConstantCode.TOKEN_EXPIRE);
        }
        return tbToken.getValue();
    }

    /**
     * update token expire time.
     */
    public void updateExpireTime(String token) {
        Assert.requireNonEmpty(token, "token is empty");
        TbToken tbToken = new TbToken();
        tbToken.setToken(token);
        tbToken.setExpireTime(LocalDateTime.now().plusSeconds(properties.getAuthTokenMaxAge()));
        tbTokenMapper.updateByPrimaryKeySelective(tbToken);
    }

    /**
     * delete token.
     */
    public void deleteToken(String token, String value) {
        log.info("deleteToken. token:{} value:{}", token, value);
        TbTokenExample example = new TbTokenExample();
        if (token != null) {
            example.createCriteria().andTokenEqualTo(token);
        }
        if (value != null) {
            example.createCriteria().andValueEqualTo(value);
        }
        tbTokenMapper.deleteByExample(example);
    }
}
